<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<style>
.dashed {
	position:relative;
	
	width:800px;
	border:2px dashed #000;
	margin-top:20px;
	margin-left:20px;
	background:#ffffcc;
}
</style>

<?php
require("lib/Util.php");
require("lib/DB/JSONDB.php");

//set dir and fields here
$dir = $DATADIR;
$fields=$DATAFIELDS;

//password("sample","laiyin");


//no modify below
$script_name=$SCRIPTNAME;
array_unshift($fields,"file");
$mode = param("mode") ?  param("mode") : "list";
$db = new JSONDB($dir);

echo "<table width=100%><tr><td><a href=$script_name>List</a><td><td align=right><a href=$script_name?logout=true>Logout</a></td></tr></table><hr>";

if($mode == "list"){
	$list = $db->file_list();
	echo "<table border=1><tr><th>file</th><th>show</th><th>edit</th></tr>";
	foreach($list as $one){
		echo "<tr><td>$one</td><td><a href='$script_name?mode=show&file=$one'>show</a></td><td><a href='$script_name?mode=edit&file=$one'>edit</a></td></tr>";
	}
	echo "</table>";
	echo "<hr><a href=$script_name?mode=add>Add</a>";
}else if($mode == "add"){
	if(is_post()){
		if(!file_exists($dir."/".param("file"))){
			$data = array();
			foreach($fields as $field){
				$data[$field]=param($field);
			}
			$db->set(param("file"),$data);
			echo "added sucessfully";
		}else{
			echo "<font color=red>exits,failed!</font>";
		}
	}
	echo "<form method=post>";
	foreach($fields as $field){
		echo "$field:<br><textarea rows=10 cols=100 name=$field>",escape(param($field)),"</textarea><br>";
	}
	echo "<input type=hidden name=mode value=add><input type=submit></form>";
}else if($mode == "show"){
	$detail = $db->get(param("file"));
	foreach($fields as $i){
		$j=$detail->$i;
		echo "<font color=blue>$i</font>:<br><div class=dashed><pre>",escape($j),"</pre></div><br>";
	}
	if(param("debug")){
		echo "<font color=blue>original</font>:<div class=dashed><pre>",file_get_contents($dir."/".param("file")),"</pre></div>";
	}
	echo "<hr><a href=$script_name?mode=edit&file=",param("file"),">Edit</a><br><br><br>";
	echo "<hr><a href=$script_name?mode=delete&file=",param("file"),"><font color=red>Delete</font></a>";
}else if($mode == "edit"){
	if(is_post()){
		if(file_exists($dir."/".param("file"))){
			$data = array();
			foreach($fields as $field){
				$data[$field]=param($field);
			}
			$db->set(param("file"),$data);
			echo "edit sucessfully";
		}else{
			echo "<font color=red>file not found!</font>";
		}
	}
	$detail = $db->get(param("file"));
	echo "<form method=post>";
	foreach($fields as $field){
		$j=$detail->$field;
		if($field == "file"){
			echo "<input type=hidden name=file value='$j'>FILE:  <font color=green size=5>$j</font><br>";
		}else{
			echo "$field:<br><textarea  rows=10 cols=100 name=$field>",escape(param($field)?param($field):$j),"</textarea><br>";
		}
	}
	echo "<input type=hidden name=mode value=edit><input type=submit></form>";
}else if($mode == "delete"){
	$db->delete(param("file"));
}else{
	echo "invalid access";
}




?>